package com.qk.web.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if ("/login".equals(req.getRequestURI())) {
            log.info("用户登录: {}", req.getParameterMap());
            chain.doFilter(req, res);
            return;
        }

        String token = req.getHeader("token");
        if (token == null || token.isEmpty()) {
            log.info("用户未登录");
            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        try {
            Claims claims = JwtUtils.parseToken(token);
            //获取用户id, 存入ThreadLocal
            Integer userId = claims.get("id", Integer.class);
            CurrentUserHoler.setCurrentUser(userId);
        } catch (Exception e) {
            log.info("用户未登录");
            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        log.info("token 正确, 继续执行后续过滤器或请求处理: {}", req.getParameterMap());
        chain.doFilter(req, res);

        //用户删除
        CurrentUserHoler.removeCurrentUser();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
